<template>
  <div class="set-authority-view" v-loading="loading">
    <div class="authority-data-view">
      <el-tree ref="tree" :data="treeData" :props="treeProps" node-key="id" :expand-on-click-node="false" show-checkbox></el-tree>
    </div>
    <div style="text-align: center;">
      <el-button type="primary" @click="setAuthority">{{$t('global.submit')}}</el-button>
      <el-button @click="cancelView">{{$t('global.cancel')}}</el-button>
    </div>
  </div>

</template>

<script>

import { getMenuTreeListByRoleId } from '@/api/menuApi.js'
import { setRoleAuthority } from '@/api/roleApi.js'

import { getMenuTreeData } from '@/common/utils/util.js'

export default {
  data(){
    return{
      loading:false,
      treeData:[],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      checkKeys:[]
    }
  },
  props: ["roleId"],
  watch:{
    roleId(newVal,oldVal){
      this.getRoleMenuList(newVal)
    },
  },
  components:{

  },
  created(){
    // this.getRoleMenuList(this.roleId)
  },
  mounted(){
    this.getRoleMenuList(this.roleId)
  },
  methods:{
    getRoleMenuList(id){            //通过roleId获取权限菜单
      getMenuTreeListByRoleId({roleId:id}).then((res)=>{
        if(res.status == 200){
          this.treeData = getMenuTreeData(res.data)
          this.setcheckKeys()
          console.log(this.treeData)
        }
      })
    },
    setcheckKeys(){             //设置权限勾选项
      this.checkKeys = []
      this.treeData.forEach((item)=>{
        if(item.checked){
          this.checkKeys.push(item.id)
        }
      })
      this.$refs.tree.setCheckedKeys(this.checkKeys);
    },
    cancelView(){
      this.$emit('cancelView')
    },
    setAuthority(){
      let auths = this.$refs.tree.getCheckedKeys()              //选中状态
      let authKeys = this.$refs.tree.getHalfCheckedKeys()       //半选中状态
      auths = auths.concat(authKeys)            //合并状态
      console.log(auths)
      if(auths.length == 0){
        this.$message.error(this.$t('role_management.permissions_error'))
        return
      }
      this.loading = true
      let formData = new FormData()
      formData.append("ids",auths.join(","))
      formData.append("roleId",this.roleId)
      setRoleAuthority(formData).then((res)=>{
        this.loading = false
        if(res.data.code == 200){
          this.$message({
            message: this.$t('global.modified_success'),
            type: 'success'
          });
          this.$emit('refreshData')
        }else{
          this.$message.error(res.data.message)
        }
      }).catch((e)=>{
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.set-authority-view{
  width: 100%;
  height: 600px;
  display: flex;
  flex-direction: column;
  .authority-data-view{
    flex: 1;
    width: 100%;
    overflow: auto;
    margin-bottom: 20px;
    margin-top: -10px;
  }
}
</style>
